package com.ikdong.toodle.dao;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.ikdong.toodle.util.Constant;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {
	private static String DB_PATH = "/data/data/com.ikdong.toodle/databases/";
	private static String DB_NAME = "YYA.mp3";
	private SQLiteDatabase myDataBase;
	private final Context myContext;
	
	private static final String DATABASE_CREATE_CONTEXT =  "CREATE TABLE IF NOT EXISTS Context(_id INTEGER PRIMARY KEY,name text,private number,status number,sig text )";
	private static final String DATABASE_CREATE_GOAL =  "CREATE TABLE IF NOT EXISTS Goal(_id INTEGER PRIMARY KEY,name text,level number,archived number,contributes number,note text,status number,sig text )";
	
	public DataBaseHelper(Context context){
		super(context, DB_NAME, null, 2);
		this.myContext = context;
		createDataBase();
	}
	
	public void createDataBase(){
		boolean dbExist = checkDataBase();
		if (!dbExist){
			try {
				SQLiteDatabase db = getReadableDatabase();
				if(db!=null) db.close();
				copyDataBase();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Check if the database already exist to avoid re-copying the file each time you open the application.
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase(){
		SQLiteDatabase checkDB = null;
		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);
		} catch (SQLiteException e) {
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	public void copyDataBase() throws IOException {
		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);
		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		File of = new File(DB_PATH);
		of.mkdir();
		of = new File(outFileName);
		of.createNewFile();
		OutputStream myOutput = new FileOutputStream(of);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		BufferedInputStream sis = new BufferedInputStream(myInput);
		while ((length = sis.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();

	}

	public void openDataBase() throws SQLException {
		// Open the database
		if(myDataBase==null || !myDataBase.isOpen()){
			String myPath = DB_PATH + DB_NAME;
			myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);
		}			
	}

	@Override
	public synchronized void close(){
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db){
		Log.d(Constant.TAG, "DataBaseHelper.onCreate()");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(Constant.TAG, "DataBaseHelper.onUpgrade()");
		if(newVersion>1){
			db.execSQL(DATABASE_CREATE_CONTEXT);		
			db.execSQL(DATABASE_CREATE_GOAL);		
		}
	}
}
